<script setup>
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import axios from 'axios';

const passwordModel = ref({
  userId: '1', // 写死的用户ID
  old_pwd: '',
  new_pwd: '',
  re_pwd: ''
});

// 验证密码是否一致
const validatePassword = () => {
  if (passwordModel.value.new_pwd !== passwordModel.value.re_pwd) {
    ElMessage.error('新密码和确认密码不一致');
    return false;
  }
  return true;
};

const updatePassword = async () => {
  if (!validatePassword()) {
    return; // 如果密码不一致，直接返回
  }

  try {
    // 构造后端接口需要的参数
    const data = {
      userId: passwordModel.value.userId,
      oldPassword: passwordModel.value.old_pwd,
      newPassword: passwordModel.value.new_pwd
    };

    // 调用接口
    const response = await axios.post('http://localhost:8080/user/updatePassword', data, {
      headers: {
        Authorization: `Bearer eyJhbGciOiJIUzI1NiJ9.eyJwaG9uZSI6IjEzODAwMTM4MDAxIiwiaWQiOjEsImlhdCI6MTc0OTgyMTI2MCwiZXhwIjoxNzQ5OTA3NjYwfQ.HvrfYhFDfE13ykvk7sCpOP8NwZWV8252tYYCkQYW7xk`
      }
    });

    // 检查后端返回的数据
    if (response.data && response.data.code === 0) {
      ElMessage.success(response.data.message ? response.data.message : '修改成功');
    } else {
      ElMessage.error(response.data.message ? response.data.message : '修改失败');
    }
  } catch (error) {
    console.error('修改密码失败:', error);
    if (error.response && error.response.data) {
      ElMessage.error(error.response.data.message || '修改失败');
    } else {
      ElMessage.error('网络错误或输入不合法');
    }
  }
};
</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>修改密码</span>
      </div>
    </template>
    <el-row>
      <el-col :span="12" :offset="5">
        <el-form :model="passwordModel" label-width="100px" size="large">
          <el-form-item label="原密码">
            <el-input v-model="passwordModel.old_pwd" type="password"></el-input>
          </el-form-item>
          <el-form-item label="新密码">
            <el-input v-model="passwordModel.new_pwd" type="password"></el-input>
          </el-form-item>
          <el-form-item label="确认密码">
            <el-input v-model="passwordModel.re_pwd" type="password"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="updatePassword">提交修改</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </el-card>
</template>